<template>
  <div>
    <h3>添加服务器租赁</h3>
    <el-divider></el-divider>
    <el-form ref="form" label-width="80px">
      <el-form-item label="租赁者">
        <el-col :xs="24" :sm="11" :md="10">
          <el-input v-model="zlyhm" :autofocus="true" clearable prefix-icon="el-icon-user" :minlength="2" :maxlength="8" placeholder="一定要输入正确的用户名哦"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="服务器IP">
        <el-autocomplete
            class="inline-input"
            v-model="ip"
            clearable
            prefix-icon="el-icon-cpu"
            :minlength="7"
            :maxlength="15"
            :fetch-suggestions="querySearch"
            placeholder="请输入服务器IP地址"
            @select="handleSelect">
          <template slot-scope="{ item }">
            <div class="name">{{ item.ip }}</div>
            <span class="addr">服务器地区:{{ item.dy }}</span>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="租赁时间">
        <el-date-picker
            v-model="zlsj"
            type="date"
            clearable
            placeholder="选择租赁到期日期"
            format="yyyy年M月d日"
            value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="add">添加租赁</el-button>
      </el-form-item>
    </el-form>


  </div>
</template>

<script>
import qs from "qs";
import {addServerLease, getServer} from "../../utils/api";
export default {
  name: "ServerLeaseAdd",
  data(){
    return {
      ip:'',
      zlyhm:'',
      zlsj:'',
      serverAll: [],
    }
  },
  methods:{
    add(){
      addServerLease(qs.stringify(
          {ip:this.ip,zlyhm:this.zlyhm,zlsj:new Date(this.zlsj).getTime()})
      ).then(respose=>{
        if(respose.status===200){
          this.$toast.success("添加成功");
        }else{
          this.$toast.fail("添加失败")
        }
      }).catch(error=>{
        console.log(error);
        this.$toast.fail("添加失败")
      })
    },
    querySearch(queryString, cb) {
      let serverAll = this.serverAll;
      let results = queryString ? serverAll.filter(this.createFilter(queryString)) : serverAll;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.ip.indexOf(queryString) === 0);
      };
    },
    handleSelect(item) {
      this.ip=item.ip
    },
  },
  created() {
    getServer().then(respose=>{
      if(respose.status==200){
        this.serverAll=respose?.body;
      }else{
        this.$message.error(respose?.msg);
      }
    }).catch(error=>{
      console.log(error);
    })
  }
}
</script>

<style scoped>
li {
  line-height: normal;
  padding: 7px;
}
.name {
  text-overflow: ellipsis;
  overflow: hidden;
  line-height: 27px;
}
.addr {
  font-size: 12px;
  color: #b4b4b4;
}

.highlighted .addr {
  color: #ddd;
}
</style>
